<?php

namespace app\order\logic;
use app\order\logic\BasicLogic;
use app\order\model\Order as OrderModel;
use think\facade\Db;

class OrderTrackLogic extends BasicLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new OrderModel();
    }

    /**
     * @desc  物流轨迹列表接口
     * @date  2024/4/17
     * @author luckyXiong
     */
    public function getOrderTrackList($params = [])
    {
        $shop_id         = $params['shop_id'] ?? [];
        $limit           = $params['limit'] ?? 10;
        $createtime      = $params['createtime'] ?? '';
        $tracking_number = $params['tracking_number'] ?? '';
        $orderId         = $params['order_id'] ?? '';
        $where           = [];
        
        if ($shop_id) {
            $where[] = ['shop_id', '=',$shop_id];
        }

        if (!empty($tracking_number)) {
            $where[] = ['tracking_number', 'like', '%' . $tracking_number . '%'];
        }
        
        if (!empty($createtime)) {
            $createtimeArr = explode(',', $createtime);
            $where[] = ['time_iso', '>=', $createtimeArr[0]];
            $where[] = ['time_iso', '<=', $createtimeArr[1]];
        }

        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order_id', 'in', $order_ids];
            }
        }

        $res = Db::name('order_track')
            ->field('sub_status,id,shop_id,order_id,sub_status as status,time_iso,tracking_number')
            ->where($where)
            ->order('time_iso desc')
            ->group('order_id')
            ->paginate($limit);

        $list = $res->items();

        $shop_ids  = array_column($list,'shop_id');

        //批量获取店铺信息及sku数量信息;
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        foreach($list as $k=>$v){
            $shop_names                =  $shopInfos_map[$v['shop_id']]??[];
            $list[$k]['shop_name']     =  $shop_names['name']??'';
            $list[$k]['createtime']    =  self::change_date_time($v['time_iso']);
            unset($list[$k]['time_iso']);
        }

        $data = [
            'list'  => $list,
            'total' => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }




    /**
     * @desc 时间格式转换
     * @date 2024-06-03
     */
    private function change_date_time($dateString=''){
        $timestamp         =  strtotime($dateString)-15*3600;
        return date("Y-m-d H:i:s", $timestamp);
    }













}